import { makeAutoObservable, observable } from 'mobx';
import * as api from './api';

export default class CompanyStore {
  _args = {
    search: {
    },
    pg: {
      page: 0,
      sort: ['crDate;desc'],
      size: 10,
    },
  };
  total = 0;
  company = [];
  loading = false;
  charges = [];
  companyName = '';
  payMerchant = [];

  constructor(rootStore) {
    this.rootStore = rootStore;
    makeAutoObservable(this, { rootStore: false });
  }

  /**
   * 使用设置的请求参数和分页配置请求列表数据
   * 分页参数为空时保持当前分页配置
   * @param {object} pgInfo 分页参数
   */
  * query(pgInfo) {
    _.mergeWith(this._args.pg, pgInfo, (o, s) => (_.isArray(o) ? s : undefined)); // 数组直接赋值，不合并
    const { search, pg } = toJS(this._args);
    // if (!pg.sort?.length) delete pg.sort;
    this.loading = true;
    try {
      this.total = yield api.count({ search });
      this.company = yield api.get({ search, pg });
    } finally {
      this.loading = false;
    }
  }
  * get(id) {
    const res = yield api.getCompany(id);
    return observable(res);
  }

  idx(i) {
    return this._args.pg.page * this._args.pg.size + i + 1;
  }

  get pg() {
    return this._args.pg;
  }

  set pg(pg) {
    this.query({ ...pg });
  }

  * create(data) {
    yield api.create({ ...data, status: data.status ? 1 : 0 });
    yield this.query();
  }

  * update(data) {
    yield api.update({ ...data, status: data.status ? 1 : 0 });
    yield this.query();
  }

  * updateStatus(data) {
    yield api.update({ ...data, status: data.status === 1 ? 0 : 1 });
    yield this.query();
  }

  * stopOrder(data) {
    yield api.stopOrder(data);
    yield this.query();
  }

  * getPayMerchant(pg) {
    const merchant = yield api.getPayMerchant(pg);
    this.payMerchant = merchant.map((item) => ({
      label: item.name,
      value: item.subMchid,
    }));
  }

  * getConsoleUser(data) {
    // const text = encodeURIComponent(
    //   `${global.getEnvCfg().codeUrl}/mp/${global.getEnvCfg().travel}/?inviteInfo=${getConsoleUser[0].inviteCode}-200`,
    // );
    // const baseUrl = `${global.getEnvCfg().baseUrl}/api/files/qrcode?text=${text}&height=300&width=300`;
    // return baseUrl;

    const getConsoleUser = yield api.getConsoleUser(data);
    const res = yield api.getQCexterior({
      path: `pages/home/index?inviteInfo=${getConsoleUser[0].inviteCode}-200&scene=company:1000`,
      env_version: global.ENV_VERSITION[global.ENV],
    });
    const blob = new Blob(
      res.map((buf) => Uint8Array.from(buf.data).buffer),
      {
        type: 'image/jpeg',
      },
    );
    const objectUrl = URL.createObjectURL(blob);
    console.log('🚀 _ file: CompanyStore.js:107 _ CompanyStore _ objectUrl:', objectUrl);
    // const url = `${baseUrl}/api/files/qrcode?text=${encodeURIComponent(
    //   `${codeUrl}/mp/${travel}/?inviteInfo=${userInfo.inviteCode}-2`,
    // )}&height=400`;
    return objectUrl;
  }

  * addProfitShare(id) {
    const res = yield api.addProfitShare('COMPANY', id);
    const { imgUrl, mpAppId, baseUrl } = global.getEnvCfg();
    // 动态展示小程序链接
    const text = encodeURIComponent(`${imgUrl}/mp/?appId=${mpAppId}&sid=${res.sid}`);
    const url = `${baseUrl}/api/files/qrcode?text=${text}&height=300&width=300`;
    return url;
  }

  get search() {
    this._args.pg.page = 0;
    return this._args.search;
  }

  set search(search) {
    this._args.pg.page = 0;
    this._args.search = search;
    this.query({ page: 0 });
  }

  get tableSort() {
    if (this._args.pg.sort?.length) {
      const [fn, dir] = this._args.pg.sort[0].split(';');
      return { [fn]: dir };
    }
    return undefined;
  }

  get api() {
    return api;
  }
}
